package DigitalNetwork;

public class NetworkController implements INetworkListener {

	private Network network = null;
	private NetworkView view = null;
	private Network.SimulatingTask task = null;

	;

	/** [Konstruktor]
	 * Letrehozza a Network-ot, es a View-t
	 *
	 */
	public NetworkController() {
		this.view = Main.drawPanel;
	}

	/**
	 *
	 * @param success
	 * @return
	 */
	public void onLoad(boolean success) {
		if (success) {
			Main.stateLabel.setText("[INFO] Sikeres betoltes");
			this.network.startSimulation(1);
		} else {
			Main.stateLabel.setText("[HIBA] Sikertelen betoltes");
		}
	}

	/**
	 *
	 * @return
	 */
	public void onIteration() {
		this.view.repaint();
	}

	/**
	 *
	 * @return
	 */
	public void startStop() {
		if (this.network != null) {
			if (task == null) {
				task = this.network.new SimulatingTask();
				task.execute();
			} else if (task.isDone()) {
				task = this.network.new SimulatingTask();
				task.execute();
			} else {
				task.cancel(true);
			}
		}
	}

	/**
	 *
	 * @return
	 */
	public void load(String fname) {
		this.view.reset();
		this.network = new Network();

		// Listenerek beallitasa
		this.network.addListener(this);
		this.network.simulator.addListener(this.view);

		// Halozatbetoltes
		network.loadNetwork(fname, false);
	}

	/**
	 *
	 * @return
	 */
	public void step() {
		if (this.network != null) {
			this.network.startSimulation(1);
		}
	}

	/**
	 *
	 * @return
	 */
	public void setInputs(String[] settings) {
		for (int i = 0; i < settings.length / 2; i++) {
			if (this.network.simulator.getSource(settings[2 * i]).getType().equals("Button")) {
				Button b = (Button) this.network.simulator.getSource(settings[2 * i]);
				if (settings[2 * i + 1].matches("[01]")) {
					boolean high = Integer.parseInt(settings[2 * i + 1]) == 1;
					b.press(high);
					step();
				} else {
					Main.stateLabel.setText("[HIBA] Hibasan megadott bemenet.");
				}
			} else if (this.network.simulator.getSource(settings[2 * i]).getType().equals("Generator")) {
				Generator gen = (Generator) this.network.simulator.getSource(settings[2 * i]);
				if (settings[2 * i + 1].matches("[01]+")) {
					boolean[] pattern = new boolean[settings[2 * i + 1].length()];
					for (int j = 0; j < settings[2 * i + 1].length(); j++) {
						pattern[j] = settings[2 * i + 1].charAt(j) == '1';
					}
					gen.setPattern(pattern);
					step();
				} else {
					Main.stateLabel.setText("[HIBA] Hibasan megadott bemenet.");
				}
			}
		}
	}

	/**
	 *
	 * @return
	 */
	public Network getNetwork() {
		return this.network;
	}
}
